package org.mobile.api;

import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.mobile.api.exception.AccessException;
import org.mobile.model.util.ServiceUtil;

import com.ucmed.hospital.common.Service;
import com.ucmed.service.invoker.NoSuchServiceException;
import com.ucmed.service.invoker.NoSuchServiceMethodException;

/**
 * @author sbwkl
 */
public class ApiFactoryImpl implements ApiFactory {

    private String app;
    
    private String version;
    
    private Map<String, Service> map;
    
    public String getApp() {
        return app;
    }

    public void setApp(String app) {
        this.app = app;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public final void setMap(Map<String, Service> map) {
        this.map = map;
    }

    @Override
    public Api getApi(String apiName) {
        final Service service = map.get(apiName);
        Api api = new Api() {

            @Override
            public JSONObject execute(JSONObject params) {
                return service.service(params);
            }
        };
        return api;
    }

    @Override
    public void validAppAccess(String appId, String appKey, Integer id)
            throws AccessException {
        try {
            if(!checkIfValid(appId, appKey, id)) {
                if(checkIfValid(appId, appKey, id)) {
                    return;
                }
            } else {
                return;
            }
            throw new AccessException("Access denied for illegal app id");
        } catch(Exception e) {
            throw new AccessException("Access denied for illegal app id");
        }
    }

    private boolean checkIfValid(String appId, String appKey, Integer id)
            throws AccessException, NoSuchServiceException,
            NoSuchServiceMethodException {


		JSONObject o = ServiceUtil.doService("appManagementService",
				"getList",null);
		if (o == null)
			throw new AccessException("service error");
		JSONArray arr = o.optJSONArray("arr");
		if (CollectionUtils.isEmpty(arr))
			throw new AccessException(
					"Access denied for illegal appId or appKey");
		for (Object object : arr) {
			JSONObject o1 = (JSONObject) object;
			if (o1.optString("appKey").equals(appKey))
				return true;
		}
		return false;
    }
}
